layui.use(['table', 'ax','laydate','admin'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var laydate = layui.laydate;
    var admin = layui.admin;
    lay('.datetime-input').each(function(){
        laydate.render({
            elem: this
            ,trigger: 'click'
            ,type: 'datetime'
        });
    });

    /**
     * 字典类型表管理
     */
    var Product = {
        tableId: "productTable"
    };

    /**
     * 初始化表格的列
     */
    Product.initColumn = function () {
        return [[
            {type: 'checkbox',fixed:"left"},
            {type:'numbers',title:"序号",fixed:"left"},
            {field: 'id', hide: true, title: '编号'},

            {field: 'productName', sort: true, title: '商品名称',fixed:'left'}
            ,{field: 'productPrice', sort: true, title: '商品市场价'}
            ,{field: 'jifen', sort: true, title: '兑换积分'}
            ,{field: 'photos', sort: true, title: '商品图片',templet:function(d){return "<img src='/upload/brand/"+d.photos+"' style='width:100px;height:100px'/>"}}
            ,{field: 'detail', sort: true, title: '商品详情'}
            ,{field: 'status', sort: true, title: '商品状态',templet:function(d){return d.statusModel.name}}
            ,{field: 'createTime', sort: true, title: '商品上架时间'}
            ,{align: 'center', toolbar: '#tableBar', title: '操作',fixed:"right",minWidth:120}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Product.search = function () {
        var queryData = {};
        queryData['productName'] = $("#productName").val();
        queryData['productPrice'] = $("#productPrice").val();
        queryData['jifen'] = $("#jifen").val();
        queryData['photos'] = $("#photos").val();
        queryData['detail'] = $("#detail").val();
        queryData['status'] = $("#status").val();
        queryData['createTime'] = $("#createTime").val();
        table.reload(Product.tableId, {where: queryData});
    };

    /**
     * 弹出添加对话框
     */
    Product.openAddDlg = function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加商品',
            content: Feng.ctxPath + '/product/add',
            area:"650px",
            end: function () {
                admin.getTempData('formOk') && table.reload(Product.tableId);
            }
        });
    };

    /**
     * 导出excel按钮
     */
    Product.exportExcel = function () {
        var checkRows = table.checkStatus(Product.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };
    Product.delItems = function () {
        var checkRows = table.checkStatus(Product.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要删除的数据");
        } else {
            var datas = checkRows.data;
            var params = [];
            for(var i=0;i<datas.length;i++){
                params.push(datas[i].id);
            }
            var paramsJson = JSON.stringify(params);
            $.ajax({
                type:"POST",
                url: Feng.ctxPath + "/product/delItems",
                dataType:"json",
                contentType:"application/json", // 指定这个协议很重要
                data:paramsJson,
                async:false,
                //只有这一个参数，json格式，后台解析为实体，后台可以直接用
                success:function(data){
                    Feng.success("删除成功!");
                    table.reload(Product.tableId);
                }
            })


        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Product.openEditDlg = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '修改商品',
            area:"650px",
            content: Feng.ctxPath + '/product/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Product.tableId);
            }
        });
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    Product.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/product/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(Product.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Product.tableId,
        url: Feng.ctxPath + '/product/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: Product.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        var validation = new Validation($("form")[0], {onSubmit:false});
        var validate = validation.validate();
        if(validate){
            Product.search();
        }else{
            var serializeArray = $(".validation-failed");
            var errMsgs = "";
            for(var i=0;i<serializeArray.length;i++){
                var elemInfo = serializeArray[i];
                var elem = $("#"+elemInfo.name)[0];
                if(elem && elem.tooltip){
                    errMsgs+="<div><span style='color:dodgerblue'>"+elem.placeholder+"输入框有误：</span><span style='color:red'>"+elem.tooltip.content+"</span></div>"
                    var tipElem = elem.tagName=="SELECT"?$(elem).next():elem;
                    layer.tips(elem.tooltip.content,tipElem,{
                        tips: [1, '#FF99CC'],
                        time: 4000,
                        tipsMore: true
                    });
                }
            }
            //Feng.error(errMsgs);
        }
        return false;
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Product.openAddDlg();
        return false;
    });
    // 导出excel
    $('#btnExp').click(function () {
        Product.exportExcel();
        return false;
    });
    $('#btnDel').click(function () {
        Product.delItems();
        return false;
    });
    Product.onShow = function(data){
        top.layui.admin.open({
            type: 2,
            title: '查看商品',
            content: Feng.ctxPath + '/product/show?id=' + data.id,
        });
    }

    // 工具条点击事件
    table.on('tool(' + Product.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Product.openEditDlg(data);
        } else if (layEvent === 'delete') {
            Product.onDeleteItem(data);
        }else if(layEvent==='show'){
            Product.onShow(data);
        }
    });
});
